<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, type Ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import {
  Search,
  DataBoard,
  OfficeBuilding,
  Grid,
  User,
  Refresh,
} from "@element-plus/icons-vue";
import { useDark, useECharts, type EchartOptions } from "@pureadmin/utils";
import { getAssetStatistics } from "@/api/task";
import * as echarts from "echarts/core";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();

defineOptions({
  name: "TerminalAsset",
});

const { isDark } = useDark();

const theme: EchartOptions["theme"] = computed(() => {
  return isDark.value ? "dark" : "light";
});

// 图表引用
const departmentChartRef = ref<HTMLDivElement | null>(null);
const categoryChartRef = ref<HTMLDivElement | null>(null);
const contactChartRef = ref<HTMLDivElement | null>(null);
const serviceTypeChartRef = ref<HTMLDivElement | null>(null);

// 图表实例
const { setOptions: setDepartmentOptions, resize: resizeDepartment } =
  useECharts(departmentChartRef as Ref<HTMLDivElement>, { theme });
const { setOptions: setCategoryOptions, resize: resizeCategory } = useECharts(
  categoryChartRef as Ref<HTMLDivElement>,
  { theme }
);
const { setOptions: setContactOptions, resize: resizeContact } = useECharts(
  contactChartRef as Ref<HTMLDivElement>,
  { theme }
);
const { setOptions: setServiceTypeOptions, resize: resizeServiceType } =
  useECharts(serviceTypeChartRef as Ref<HTMLDivElement>, { theme });

// 统计数据
const statisticsData = ref({
  department_distribution: [],
  department_total_types: 0,
  application_category_distribution: [],
  report_contact_distribution: [],
  total_assets: 0,
  // 添加实际返回的字段
  asset_type_distribution: [],
  responsible_person_distribution: [],
  service_type_distribution: [],
  ip_version_distribution: {},
  top_10_ports: [],
  cross_department_assets: 0,
  web_interface_assets: 0,
});

const loading = ref(false);

// 获取统计数据
const fetchStatistics = async () => {
  try {
    loading.value = true;
    console.log("开始获取统计数据...");

    // 确保参数格式正确
    const requestData = {
      asset_model_type: "application",
    };

    console.log("请求参数:", requestData);

    const response = await getAssetStatistics(requestData);

    console.log("API响应:", response);

    if (response.code === 2000) {
      console.log("数据获取成功:", response.data);
      statisticsData.value = response.data;
      nextTick(() => {
        drawCharts();
      });
    } else {
      console.error("API返回错误:", response.message);
      // 显示错误信息
      ElMessage.error(`获取数据失败: ${response.message || "未知错误"}`);
    }
  } catch (error) {
    console.error("获取统计数据失败:", error);
    ElMessage.error("网络请求失败，请检查网络连接");

    // 使用模拟数据进行测试
    console.log("使用模拟数据进行测试...");
    statisticsData.value = {
      department_distribution: [
        { department: "技术部", count: 25 },
        { department: "运维部", count: 18 },
        { department: "研发部", count: 32 },
      ],
      department_total_types: 3,
      application_category_distribution: [],
      report_contact_distribution: [],
      total_assets: 90,
      asset_type_distribution: [
        { asset_type: "IPv4", count: 60 },
        { asset_type: "IPv6", count: 30 },
      ],
      responsible_person_distribution: [
        { person: "张三", asset_count: 25 },
        { person: "李四", asset_count: 20 },
        { person: "王五", asset_count: 18 },
      ],
      service_type_distribution: [
        { service_type: "HTTP", count: 40 },
        { service_type: "HTTPS", count: 30 },
      ],
      ip_version_distribution: {
        ipv4: { count: 60, percentage: 66.7 },
        ipv6: { count: 30, percentage: 33.3 },
        total: 90,
      },
      top_10_ports: [
        { port: 80, count: 40 },
        { port: 443, count: 30 },
      ],
      cross_department_assets: 5,
      web_interface_assets: 20,
    };

    nextTick(() => {
      drawCharts();
    });
  } finally {
    loading.value = false;
  }
};

// 绘制部门分布柱状图
const drawDepartmentChart = () => {
  const data = statisticsData.value.department_distribution;

  if (!data || data.length === 0) {
    console.log("部门分布数据为空，显示空状态");
    setDepartmentOptions({
      title: {
        text: "部门资产分布",
        left: "left",
        textStyle: {
          color: "#13c2c2",
          fontWeight: "normal",
        },
      },
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: "暂无数据",
          fontSize: 16,
          fill: "#999",
        },
      },
    });
    return;
  }

  const departments = data.map((item) => item.department);
  const counts = data.map((item) => item.count);

  console.log("绘制部门分布图:", { departments, counts });

  setDepartmentOptions({
    title: {
      text: "部门资产分布",
      left: "left",
      textStyle: {
        color: "#13c2c2",
        fontWeight: "normal",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      bottom: "80px", // 增加底部空间
      right: "10px",
      left: "60px", // 增加左侧空间
    },
    xAxis: {
      type: "category",
      data: departments,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 10, // 减小字体
        width: 100, // 设置标签宽度
        overflow: "truncate", // 超出部分截断
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "资产数量",
        type: "bar",
        barWidth: 10, // 设置固定宽度10px
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#409EFF" },
            { offset: 1, color: "#53a7ff" },
          ]),
        },
        data: counts,
      },
    ],
  });
};

// 绘制应用类别饼图 - 使用实际返回的asset_type_distribution
const drawCategoryChart = () => {
  const rawData = statisticsData.value.asset_type_distribution;

  if (!rawData || rawData.length === 0) {
    console.log("资产类型数据为空，显示空状态");
    setCategoryOptions({
      title: {
        text: "资产类型分布",
        left: "left",
        textStyle: {
          color: "#13c2c2",
          fontWeight: "normal",
        },
      },
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: "暂无数据",
          fontSize: 16,
          fill: "#999",
        },
      },
    });
    return;
  }

  const data = rawData.map((item) => ({
    name: item.asset_type,
    value: item.count,
  }));

  console.log("绘制资产类型饼图:", data);

  setCategoryOptions({
    title: {
      text: "资产类型分布",
      left: "left",
      textStyle: {
        color: "#13c2c2",
        fontWeight: "normal",
      },
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "middle",
    },
    series: [
      {
        name: "资产类型",
        type: "pie",
        radius: "70%",
        center: ["40%", "50%"],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  });
};

// 绘制联系人资源占用柱状图 - 使用实际返回的responsible_person_distribution
const drawContactChart = () => {
  const data = statisticsData.value.responsible_person_distribution;

  if (!data || data.length === 0) {
    console.log("负责人数据为空，显示空状态");
    setContactOptions({
      title: {
        text: "负责人资源占用",
        left: "left",
        textStyle: {
          color: "#13c2c2",
          fontWeight: "normal",
        },
      },
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: "暂无数据",
          fontSize: 16,
          fill: "#999",
        },
      },
    });
    return;
  }

  const contacts = data.map((item) => item.person);
  const counts = data.map((item) => item.asset_count);

  console.log("绘制负责人资源占用图:", { contacts, counts });

  setContactOptions({
    title: {
      text: "负责人资源占用",
      left: "left",
      textStyle: {
        color: "#13c2c2",
        fontWeight: "normal",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      bottom: "100px", // 增加更多底部空间
      right: "10px",
      left: "60px", // 增加左侧空间
    },
    xAxis: {
      type: "category",
      data: contacts,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 10, // 减小字体
        width: 80, // 设置标签宽度
        overflow: "truncate", // 超出部分截断
        formatter: function (value) {
          // 如果名称太长，截断并显示省略号
          if (value.length > 8) {
            return value.substring(0, 8) + "...";
          }
          return value;
        },
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "资产数量",
        type: "bar",
        barWidth: 10, // 设置固定宽度10px
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#e6a23c" },
            { offset: 1, color: "#eebe77" },
          ]),
        },
        data: counts,
      },
    ],
  });
};

// 绘制服务类型分布柱状图
const drawServiceTypeChart = () => {
  const data = statisticsData.value.service_type_distribution;

  if (!data || data.length === 0) {
    console.log("服务类型数据为空，显示空状态");
    setServiceTypeOptions({
      title: {
        text: "服务类型分布",
        left: "left",
        textStyle: {
          color: "#13c2c2",
          fontWeight: "normal",
        },
      },
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: "暂无数据",
          fontSize: 16,
          fill: "#999",
        },
      },
    });
    return;
  }

  const serviceTypes = data.map((item) => item.service_type);
  const counts = data.map((item) => item.count);

  console.log("绘制服务类型分布图:", { serviceTypes, counts });

  setServiceTypeOptions({
    title: {
      text: "服务类型分布",
      left: "left",
      textStyle: {
        color: "#13c2c2",
        fontWeight: "normal",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      bottom: "60px", // 服务类型名称通常较短，不需要太多空间
      right: "10px",
      left: "60px",
    },
    xAxis: {
      type: "category",
      data: serviceTypes,
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 12,
        width: 80,
        overflow: "truncate",
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "服务数量",
        type: "bar",
        barWidth: 10, // 设置固定宽度10px
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#67C23A" },
            { offset: 1, color: "#85ce61" },
          ]),
        },
        data: counts,
      },
    ],
  });
};

// 绘制所有图表
const drawCharts = () => {
  drawDepartmentChart();
  drawCategoryChart();
  drawContactChart();
  drawServiceTypeChart();
};

onMounted(() => {
  fetchStatistics();
});
</script>

<template>
  <div class="terminal-asset-container">
    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <div class="cards-header">
        <h3>资产统计概览</h3>
        <el-button
          type="primary"
          :loading="loading"
          @click="fetchStatistics"
          :icon="Refresh"
        >
          刷新数据
        </el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statisticsData.total_assets }}</div>
              <div class="stat-label">总资产数量</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#409EFF">
                <DataBoard />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.department_total_types }}
              </div>
              <div class="stat-label">部门种类</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#67C23A">
                <OfficeBuilding />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.asset_type_distribution.length }}
              </div>
              <div class="stat-label">资产类型</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#E6A23C">
                <Grid />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.responsible_person_distribution.length }}
              </div>
              <div class="stat-label">负责人</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#F56C6C">
                <User />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行统计卡片 -->
      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.service_type_distribution.length }}
              </div>
              <div class="stat-label">服务类型</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#909399">
                <Grid />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.top_10_ports.length }}
              </div>
              <div class="stat-label">开放端口</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#E6A23C">
                <DataBoard />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.cross_department_assets }}
              </div>
              <div class="stat-label">跨部门资产</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#67C23A">
                <OfficeBuilding />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">
                {{ statisticsData.web_interface_assets }}
              </div>
              <div class="stat-label">Web界面资产</div>
            </div>
            <div class="stat-icon">
              <el-icon size="40" color="#409EFF">
                <DataBoard />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container" v-loading="loading">
      <el-row :gutter="20">
        <!-- 部门分布柱状图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <div
              ref="departmentChartRef"
              class="chart"
              style="height: 450px"
            ></div>
          </el-card>
        </el-col>

        <!-- 应用类别饼图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <div
              ref="categoryChartRef"
              class="chart"
              style="height: 450px"
            ></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 负责人资源占用柱状图 -->
        <el-col :span="24">
          <el-card class="chart-card">
            <div
              ref="contactChartRef"
              class="chart"
              style="height: 500px"
            ></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 服务类型分布柱状图 -->
        <el-col :span="24">
          <el-card class="chart-card">
            <div
              ref="serviceTypeChartRef"
              class="chart"
              style="height: 500px"
            ></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.terminal-asset-container {
  height: 100%;
  padding: 20px;
}

.overview-cards {
  margin-bottom: 20px;
}

.cards-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
  }
}

.stat-card {
  height: 120px;
  position: relative;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  line-height: 1;
}

.stat-icon {
  opacity: 0.8;
}

.charts-container {
  margin-top: 20px;
}

.chart-card {
  height: 500px; // 增加卡片高度

  :deep(.el-card__body) {
    padding: 20px;
    height: calc(100% - 40px);
  }
}

.chart {
  width: 100%;
}

// 响应式设计
@media (max-width: 768px) {
  .terminal-asset-container {
    padding: 10px;
  }

  .overview-cards {
    .el-col {
      margin-bottom: 10px;
    }
  }

  .charts-container {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .stat-number {
    font-size: 24px;
  }

  .chart-card {
    height: 350px;
  }
}
</style>
